<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Member_Profile extends MY_Controller {

    public function index() {
        //$this->output->enable_profiler(TRUE);
		define("LOGIN_NOT_REQUIRED", false);
		define("LOGIN_REQUIRED", true);
		define("ID_SEGMENT", 3);
        
		$profile_id = $this->uri->segment(ID_SEGMENT);

		if (!$profile_id) {	
			$form_basic_info = $this->_set_form_basics(LOGIN_REQUIRED);
			$profile_id = $this->session->userdata('member_id');
		}
		else
			$form_basic_info = $this->_set_form_basics(LOGIN_NOT_REQUIRED);
			

		$bio = $this->_get_bio_information($profile_id);
		$car_history = $this->_load_car_history($profile_id);
        
		$data = array_merge($form_basic_info, $bio,$car_history);
        
		//Check flash data to see if there is any text to display to the user 
		$deleted_info = $this->session->flashdata('deleted_info');
		$data['deleted_info'] =	$deleted_info;

		$data['is_read_only'] = ($profile_id != $this->session->userdata('member_id'));
		
		$data['additional_javascript_references'] = '<script type="text/javascript" src="'.base_url().'js/member_car_grid_functions.js"></script>';

		$data['additional_javascript_doc_ready_functions'] = 'getGridDocReady();';
		$data['title'] = 'Central Alabama VW Club -- Member Profile';
		$data['heading'] = 'Member Profile';
        
        $data['view'] = 'member_profile_view';
        $this->load->vars($data);
        $this->load->view('master_view', $data);
    }
    public function update_password() {
        //$this->output->enable_profiler(TRUE);
        $data = array(	'member_id'			=>	$this->session->userdata('member_id'),
						'existing_password'				=>	$this->input->post('existing_password'),
						'new_password'			=>	$this->input->post('new_password'),
						'retype_password'		=>	$this->input->post('retype_password')
					);
        

            
        if ($data['new_password'] != $data['retype_password']) {
            $this->session->set_flashdata('pw_message', 'New and retyped passwords do not match.');
            redirect('member_profile/edit_bio');
        }
        
        if (strlen($data['existing_password']) == 0 || 
                strlen($data['new_password']) == 0 || 
                strlen($data['retype_password']) == 0) {
            $this->session->set_flashdata('pw_message', 'Blank passwords not allowed.');
            redirect('member_profile/edit_bio');
            
        }
        
        $this->load->model('Login_model');
        
        $is_valid_login = $this->Login_model->check_login($data['existing_password']);
        
        if (!$is_valid_login) {
            $this->session->set_flashdata('pw_message', 'Existing password incorrect.');
            redirect('member_profile/edit_bio');            
        }
            
        $this->Login_model->update_login($data['new_password']);

        $this->session->set_flashdata('pw_message', 'Password updated.');
        
        redirect('member_profile/edit_bio');
        return;
    }
	public function edit_bio() {
        //$this->output->enable_profiler(TRUE);
        $this->load->helper('form');
		$form_basic_info = $this->_set_form_basics();	
        $this->load->model('Lookup_model');

		$bio = $this->_get_bio_information();
        $lookup_data['contact_lookup'] = set_lookup($this->Lookup_model->Load_lookup_info('Contact Method'),'lookup_id','short_name');
		$data = array_merge($form_basic_info, $bio, $lookup_data);
        
        $data['pw_message'] = $this->session->flashdata('pw_message');
                
        $pw_box = array(
              'name'        => 'existing_password',
              'id'          => '_existingPassword',
              'value'       => '',
            );
        $data['existing_password'] = form_password($pw_box);
        
        $pw_box['name'] = 'new_password';
        $pw_box['id'] = '_newPassword';
        $data['new_password'] = form_password($pw_box);
        
        $pw_box['name'] = 'retype_password';
        $pw_box['id'] = '_retypePassword';
        $data['retype_password'] = form_password($pw_box);
        
        
		$data['additional_javascript_doc_ready_functions'] = 'member_profile_edit_doc_ready();';
		
		$data['is_data_form']	= true;
		$data['title']			= 'Central Alabama VW Club -- Edit Member Profile';
		$data['heading']		= 'Edit Member Profile';
        $data['view']			= 'member_profile_edit';
        $this->load->vars($data);
        $this->load->view('master_view', $data);
	
	}
    function delete_car() {
        $this->load->model('Member_model');
        define("ID_SEGMENT", 3);
        
        $car_id = $this->uri->segment(ID_SEGMENT);
        
        $car_image_array = $this->Member_model->Get_member_car_photos($car_id);
        
        //remove any images associated with the car
        foreach ($car_image_array as $array_row) {
            $this->_delete_image($array_row['mcg_id']);
        }
        
        //Delete the car
        $this->Member_model->Delete_member_car($car_id);
        
        redirect(base_url().'index.php?/member_profile');
        
        return;
    }
	function update_bio() {
        //$this->output->enable_profiler(TRUE);
		$data = $this->_get_form_post_data();
		$this->Member_model->Update_member($data);
		redirect(base_url().'index.php?/member_profile');
        return;
	}
	public function update_profile_pic() {
		
		$this->load->helper(array('form', 'url'));
		
		$data = $this->_set_form_basics();
		$data['cancel_onclick_script']	=	'window.location=\''.base_url().'index.php?/member_profile'.'\';';
		$data['is_data_form']	= true;
		
		$data['first_name']	=	$this->first_name;
		$data['title']		=	'Central Alabama VW Club -- Update Profile Picture';
		$data['heading']	=	'Update Profile Picture';
		$data['message']		=	$deleted_info = $this->session->flashdata('message');
        
        $data['view'] = 'member_profile_update_profile_pic';
        $this->load->vars($data);
        $this->load->view('master_view', $data);
		
	}	
	function do_upload()
	{
        //$this->output->enable_profiler(TRUE);
		$this->load->helper(array('form', 'url'));
        
		$data = $this->_set_form_basics();
		
		$data['is_data_form']	= true;
		$data['first_name']	=	$this->first_name;
		$data['title']		=	'Central Alabama VW Club -- Update Profile Picture';
		$data['heading']	=	'Update Profile Picture';
		
		$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '5120'; //5 meg max
		
		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload())
		{
			$this->session->set_flashdata('message', $this->upload->display_errors());
			$this->update_profile_pic();
            return;
		}
		
        $upload_data	=	$this->upload->data();
        $new_image_name = $this->process_image($upload_data['file_name'],'profile_photos', 300, 400);
        if($new_image_name == '')
        {
            $data['error']	=	'Could not process image.';
            $data['view']	=	'member_profile_update_profile_pic';	
            $this->load->vars($data);
            $this->load->view('master_view', $data);
        }
        
        $bio = $this->_get_bio_information();
        if ($bio['profile_pic'] != 'no_prof.jpg') {
            unlink($_SERVER['DOCUMENT_ROOT'].'/profile_photos/'.$bio['profile_pic']);
            $pic_name = str_replace('.jpg','_thumb.jpg',$bio['profile_pic']);
            unlink($_SERVER['DOCUMENT_ROOT'].'/profile_photos/thumbnail/'.$pic_name);
        }

        
		$this->load->model('Member_model');
		$this->Member_model->Update_member(array(	'member_id'		=>	$this->session->userdata('member_id'),
													'profile_pic' => $new_image_name));
		
		redirect(base_url().'index.php?/member_profile');
	}
    function _delete_image($photo_id) {

        $this->load->model('Car_model');
        $row = $this->Car_model->Get_car_image($photo_id);
        $pic_name = $row->pic_name;
        unlink($_SERVER['DOCUMENT_ROOT'].'/member_car_gallery/'.$pic_name.'.jpg');
        unlink($_SERVER['DOCUMENT_ROOT'].'/member_car_gallery/thumbnail/'.$pic_name.'_thumb.jpg');
        $this->Car_model->Delete_car_image($photo_id);
        
        return;
    }
	function _set_form_basics($must_be_logged_in = true) {
        
		if ($must_be_logged_in && !$this->logged_in) {
                $message    =   'You must be logged in to view your profile';
                $this->session->set_flashdata('message', $message);
                redirect('login');
        }
		
		$ret_val = '';
        $ret_val['logged_in']  = $this->logged_in;
        $ret_val['is_admin']   = $this->is_admin;
        
		return $ret_val;
	}
	function _get_bio_information($member_id = NULL) {
		$this->load->model('Member_model');
        
		$member_id = $member_id != NULL ? $member_id : $this->session->userdata('member_id');;
        $member_row = $this->Member_model->Load_member_info($member_id);
        
        //Set the values for the Member Profile
		$ret_val['member_id']		=	$member_row->member_id;
		$ret_val['email']			=   $member_row->email; 
		$ret_val['last_name']		=   $member_row->last_name;
		$ret_val['first_name']		=	$member_row->first_name;
		$ret_val['spouse_name']		=	$member_row->spouse_name;
		$ret_val['dependents']		=	$member_row->dependents;
		$ret_val['address']			=	$member_row->address;
		$ret_val['city']			=	$member_row->city;
		$ret_val['state']           =	$member_row->state;
		$ret_val['zip']             =	$member_row->zip;
		$ret_val['phone']           =	$member_row->phone;
        $ret_val['facebook_username']	=	$member_row->facebook_username;
        $ret_val['twitter_username']	=	$member_row->twitter_username;
        $ret_val['contact_method_id']	=	$member_row->contact_method_id;
		$ret_val['email']               =	$member_row->email;
		$ret_val['profile_pic']         =	$member_row->profile_pic === '' ? 'no_prof.jpg' : $member_row->profile_pic;
		
		return $ret_val;
	}	
	function _get_form_post_data()
	{
		$this->load->helper('date');
		$this->load->model('Member_model');

		$data = array(	'member_id'			=>	$this->session->userdata('member_id'),
						'email'				=>	$this->input->post('email'),
						'last_name'			=>	$this->input->post('last_name'),
						'first_name'		=>	$this->input->post('first_name'),			
						'spouse_name'		=>	$this->input->post('spouse_name'),			
						'dependents'		=>	$this->input->post('dependents'),			
						'address'			=>	$this->input->post('address'),			
						'city'				=>	$this->input->post('city'),
						'state'				=>	$this->input->post('state'),
						'zip'				=>	$this->input->post('zip'),
						'phone'				=>	$this->input->post('phone'),
                        'facebook_username'	=>	$this->input->post('facebook_username'),
                        'twitter_username'	=>	$this->input->post('twitter_username'),
                        'contact_method_id'	=>	$this->input->post('contact_method_id'),
						'modified_date'		=>	date("Y-m-d H:i:s"),
						'modified_by'		=>	$this->first_name,
					);
	
		return $data;
	}
	function _load_car_history($member_id)
	{
		
		$member_id = $member_id != NULL ? $member_id : $this->session->userdata('member_id');
		$read_only = $member_id != $this->session->userdata('member_id');
		
		$data = '';
		
		$data['add_link']		= '<input class="GridButton" id="_gridAddTop" type="image" border="0" language="javascript" onclick="return false;" alt="Insert" title="Insert" src="'.base_url().'images/add.png"  style="cursor: pointer;"/>';
		$data['view_link']		= '<input class="GridButton" id="_gridViewTop" type="image" disabled="disabled" border="0" language="javascript" onclick="return false;" alt="View" title="View" src="'.base_url().'images/view_disabled.png"  style="cursor: pointer;"/>';
		$data['copy_link']		= '<input class="GridButton" id="_gridCopyTop" type="image" disabled="disabled" border="0" language="javascript" onclick="return false;" alt="Copy" title="Copy" src="'.base_url().'images/copy_disabled.png"  style="cursor: pointer;"/>';
		$data['delete_link']	= '<input class="GridButton" id="_gridDeleteTop" type="image" disabled="disabled" border="0" language="javascript" onclick="return false;" alt="Delete" title="Delete" src="'.base_url().'images/delete_disabled.png"  style="cursor: pointer;"/>';
		
		$this->load->library('table');
		$this->table->set_heading('','Image','Nickname','Year','Model','Engine','Owned From','Owned To','For Sale');
		$this->load->model('Member_model');
		$car_history_array = $this->Member_model->Get_member_car_history($member_id);
		
		//loop through the results and checkbox the id
		foreach($car_history_array as $row) {
			$destination_link = $read_only ? 'index' : 'edit_car' ;
			$row['nickname'] = anchor(base_url().'index.php?/member_car/'.$destination_link.'/'.$row['car_id'],($row['nickname'] == '' ? 'No NickName' : $row['nickname']));
			$row['car_id']= '<input class="GridRadio" type="radio" name="car_group" id="car_group_chkIntervention'.$row['car_id'].'" >';
					 $this->table->add_row($row);
		}
		
		$local_table_template = set_table_template();
		$this->table->set_template($local_table_template); 
		$local_table = $this->table->generate();
		$data['car_history'] = $local_table;
		
		return $data;
	}

}						
/* End of file member_profile.php */
/* Location: ./application/controllers/member_profile.php */